package com.lwy.security;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.filter.CorsFilter;

/**
 * 全局跨域配置
 */
@Configuration
public class GlobalCrosConfig {

    /**
     * 跨域请求过滤器
     * @return
     */
    @Bean
    public CorsFilter corsFilter(){
        // 跨域配置
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 允许的请求方式：post请求
        corsConfiguration.addAllowedMethod("*");
        // 允许服务/地址可以访问：http:localhost:8080
        corsConfiguration.addAllowedOriginPattern("*");
        // 允许哪些请求头可以访问：
        corsConfiguration.addAllowedHeader("*");
        // 允许携带凭证
        corsConfiguration.setAllowCredentials(true);

        // 基于URL地址的跨域请求配置
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        // 注册跨域配置：哪些url地址会被拦截，检查是否符合跨域的标准
        urlBasedCorsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

        // 配置过滤器
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }

}
